import './OrderList.scss';
import { useEffect, useState } from 'react';
import { OrderItem, Page } from '@/type/orderType';
import { Spin, Button, Form, message, Select, Table, Pagination } from 'antd';
import { fetchPatientAPI } from '@/api/hospitalAPI/bookingAPI';
import { fetchOrderListAPI, fetchOrderStatusListAPI } from '@/api/memberAPI/orderListAPI';


export const OrderList = () => {
  // 获取订单列表分页参数
  const [page, setPage] = useState<Page>({ page: 1, limit: 10, patientId: undefined, orderStatus: undefined });
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState(false);
  // 就诊人列表
  const [patientList, setPatientList] = useState<{ label: string, value: number }[]>([]);
  // 订单列表
  const [orderList, setOrderList] = useState<OrderItem[]>([]);
  const columns = [
    {
      title: '就诊时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '医院',
      dataIndex: 'hosname',
      key: 'hosname',
    },
    {
      title: '科室',
      dataIndex: 'depname',
      key: 'depname',
    },
    {
      title: '医生',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '医事服务费',
      dataIndex: 'amount',
      key: 'amount',
    },
    {
      title: '就诊人',
      dataIndex: 'patientName',
      key: 'patientName',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
    },
    {
      title: '操作',
      render: (_: any, record: any) => <Button type="primary">详情</Button>,
    },
  ];
  // 订单状态列表
  const [orderStatusList, setOrderStatusList] = useState<{ label: string, value: number }[]>([]);

  /**
   * @description 获取就诊人列表的回调函数
   * */
  const fetchPatient = async () => {
    try {
      const { data } = await fetchPatientAPI();
      const patientArray = data.map(item => ({ label: item.name, value: item.id }));
      setPatientList(patientArray);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 获取挂号订单列表的回调函数
   * */
  const fetchOrderList = async (page: Page) => {
    try {
      setLoading(true);
      const { data: { records, total } } = await fetchOrderListAPI(page);
      setTotal(total);
      setOrderList(records);
    } catch (error: any) {
      message.error(error.message);
    } finally {
      setLoading(false);
    }
  };
  /**
   * @description 获取挂号订单状态的回调函数
   * */
  const fetchOrderStatusList = async () => {
    try {
      const { data } = await fetchOrderStatusListAPI();
      const statusArray = data.map(item => ({ label: item.comment, value: item.status }));
      setOrderStatusList(statusArray);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @descriptione 下拉框发生变化的回调函数
   * */
  const onChange = (value: any, option: any, flag: boolean) => {
    if (flag) {
      const newPage = {
        ...page,
        patientId: value,
      };
      setPage(newPage);
    } else {
      const newPage = {
        ...page,
        orderStatus: value,
      };
      setPage(newPage);
    }
  };

  /**
   * @description 点击查询订单按钮的回调函数
   * */
  const findOrder = async () => {
    await fetchOrderList(page);
  };

  /**
   *@description 分页器发生变化的回调函数
   * */
  const changePagination = async (_page: number, limit: number) => {
    const newPage = { ...page, limit: limit, page: _page };
    setPage(newPage);
    await fetchOrderList(newPage);
  };

  const renderTable = () => {
    if (loading) {
      return (<Spin size="large" spinning={loading}></Spin>);
    } else {
      return (
        <Table dataSource={orderList} columns={columns} pagination={false} bordered />
      );
    }
  };
  useEffect(() => {
    Promise.all([fetchPatient(), fetchOrderStatusList(), fetchOrderList(page)]);
  }, []);


  return (
    <div className="order-list">
      <div className="header">
        <h2>挂号订单列表</h2>
      </div>
      <div className="form">
        <Form layout="inline">
          <Form.Item label="就诊人">
            <Select placeholder="请选择就诊人" style={{ width: 200 }} options={patientList} onChange={(value, option) => onChange(value, option, true)} />
          </Form.Item>
          <Form.Item label="订单状态">
            <Select placeholder="请选择订单状态" style={{ width: 200 }} options={orderStatusList} onChange={(value, option) => onChange(value, option, false)} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={findOrder}>查询订单</Button>
          </Form.Item>
        </Form>
      </div>
      <div className="table">
        {
          renderTable()
        }
      </div>
      <div className="pagination">
        <Pagination
          showSizeChanger
          onChange={changePagination}
          defaultCurrent={page.page}
          total={total}
        />
      </div>
    </div>
  );
};

export default OrderList;
